package com.itheima.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuMapper;
import com.itheima.dao.PermissionMapper;
import com.itheima.dao.RoleMapper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @version v1.0
 * @author： 邱敏
 * @date： 2020/2/11 16:38
 * @description：
 */
@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {


    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuMapper menuMapper;


    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Page page = PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        List<Role> roleList = roleMapper.findPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),roleList);
    }

    @Override
    public Result findMenuAndPermission() {
        //也可以返回一个Role对象
        HashMap<String, Object> map = new HashMap<>();
        List<Permission> permissionList = null;
        try {
            //所有的权限
            permissionList = permissionMapper.findAll();
            //菜单,先查一级,在查他下边的,最多三级
            //LinkedHashSet<Menu> stairMenuLinkedHashSet = findMenuAll();
            //优化
            List<Menu> menuList = menuMapper.queryAll();
            map.put("permissionList",permissionList);
            map.put("menuList", menuList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "初始化权限信息失败");
        }
        return new Result(true,"",map);
    }

    @Override
    public Result add(Role role) {
        try {
            //先添加角色返回主键,在添加权限,菜单
            roleMapper.add(role);
            Integer roleId = role.getId();
            List<Integer> permissionIds = role.getPermissionIds();
            List<Integer> menuIdList = role.getMenuIdS();
            //检查在menuIdList中的子菜单的父菜单id是否在集合中,如若没有,查出来,加上去
            List<Integer> menuIds = jianCha(menuIdList);
            //添加权限
            setRoleAndPermission(roleId,permissionIds);
            //添加菜单
            setRoleAndMenu(roleId,menuIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "添加角色失败");
        }
        return new Result(true, "添加角色成功");
    }


    @Override
    public Result findById(Integer id) {
        Role role = null;
        try {
            role = roleMapper.findById(id);
            List<Permission> permissionList = permissionMapper.findAll();
            //所有的菜单
//            LinkedHashSet<Menu> menuLinkedHashSet = findMenuAll();
            List<Menu> menuList = menuMapper.queryAll();
//            LinkedHashSet<Menu> menuLinkedHashSet = (LinkedHashSet<Menu>) menuMapper.queryAll();
            List<Integer> permissionIds = permissionMapper.findByRoleId(id);
            List<Integer> menuIds = menuMapper.findByRoleId(id);
            role.setPermissionList(permissionList);
//            role.setMenus(menuLinkedHashSet);
            role.setMenuList(menuList);
            role.setPermissionIds(permissionIds);
            role.setMenuIdS(menuIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"数据初始化失败");
        }
        return new Result(true,"",role);
    }

    @Override
    public Result edit(Role role) {
        Integer roleId = role.getId();
        List<Integer> permissionIds = role.getPermissionIds();
        List<Integer> menuIdList = role.getMenuIdS();
        try {
            //先修改基本信息
            roleMapper.editEssentialById(role);
            //在删除所有拥有的权限和菜单
            permissionMapper.deleteByRoleId(roleId);
            menuMapper.deleteByRoleId(roleId);
            //检查后再重新加
            List<Integer> menuIds = jianCha(menuIdList);
            setRoleAndPermission(roleId,permissionIds);
            setRoleAndMenu(roleId,menuIds);
        } catch (Exception e) {
            e.printStackTrace();
            new Result(false, "修改角色信息失败");
        }
        return new Result(true, "修改角色信息成功");
    }

    @Override
    public Result delete(Integer id) {
        try {
            //先删角色相关的权限和菜单再删角色
            permissionMapper.deleteByRoleId(id);
            menuMapper.deleteByRoleId(id);
            Integer count = roleMapper.deleteRoteById(id);
            if (count == 0) {
                return new Result(false, "删除角色失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "出异常,删除角色失败");
        }
        return new Result(true, "删除成功");
    }

    /**
     * 获取角色id对应的菜单id
     * @param roleId
     * @return
     */
    @Override
    public List<Integer> getMenus(Integer roleId) {
        return roleMapper.getMenus(roleId);
    }

    private void setRoleAndMenu(Integer roleId, List<Integer> menuIdS) {
        if (CollectionUtil.isNotEmpty(menuIdS)) {
            List<Map> batchParams = new ArrayList<>();
            for (Integer menuId : menuIdS) {
                HashMap<String, Integer> map = new HashMap<>();
                map.put("roleId", roleId);
                map.put("menuId",menuId);
                batchParams.add(map);
            }
            roleMapper.setRoleAndMenu(batchParams);
        }
    }

    private void setRoleAndPermission(Integer roleId, List<Integer> permissionIds) {
        if (CollectionUtil.isNotEmpty(permissionIds)) {
            List<Map> batchParams = new ArrayList<>();
            for (Integer permissionId : permissionIds) {
                HashMap<String, Integer> map = new HashMap<>();
                map.put("roleId", roleId);
                map.put("permissionId",permissionId);
                batchParams.add(map);
            }
            roleMapper.setRoleAndPermission(batchParams);
        }
    }

    private LinkedHashSet<Menu> findMenuAll() {
        LinkedHashSet<Menu> stairMenuList = menuMapper.findStairMenu();
        if (CollectionUtil.isNotEmpty(stairMenuList)) {
            for (Menu menu : stairMenuList) {
                List<Menu> submenuList = menuMapper.findSubmenuByStairId(menu.getId());
                if (CollectionUtil.isNotEmpty(submenuList)) {
                    for (Menu submenuMenu : submenuList) {
                        List<Menu> superSubmenuList = menuMapper.findSubmenuByStairId(submenuMenu.getId());
                        submenuMenu.setChildren(superSubmenuList);
                    }
                }
                menu.setChildren(submenuList);
            }
        }
        return stairMenuList;
    }

    private List<Integer> jianCha(List<Integer> menuIdList) {
        LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>();
        for (Integer menuId : menuIdList) {
            Integer stairId =  menuMapper.findParentMenuId(menuId);
            if (stairId != null) {
                //说明此项菜单不是一级菜单,将他的父级菜单id加到集合
                linkedHashSet.add(stairId);
            }
        }
        //遍历取出来,看List里头包含没有
        for (Integer integer : linkedHashSet) {
            if (!menuIdList.contains(integer)) {
                menuIdList.add(integer);
            }
        }
        return menuIdList;
    }

}
